package xx.iverson.school_manage.service.impl;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xx.iverson.school_manage.log.Loggable;
import xx.iverson.school_manage.mapper.PointsMapper;
import xx.iverson.school_manage.mapper.UserMapper;
import xx.iverson.school_manage.service.UserService;
import xx.iverson.school_manage.entity.User;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * @author wei77
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private PointsMapper pointsMapper;

    @Override
    public boolean login(String username, String password, String role) {
        return userMapper.login(username, password, role) > 0;
    }

    @Override
    public User getUser(String username) {
        return userMapper.selectUser(username);
    }


    @Override
    public User getUserByUserId(Integer userId) {
        return userMapper.selectUserByUserId(userId);
    }

    @Override
    @Loggable("修改密码")
    public boolean updatePassword(Integer userId, String newPassword) {
        return userMapper.updatePassword(userId, newPassword) != null;
    }

    @Transactional
    @Override
    @Loggable("添加用户")
    public boolean addUser(String username, String role, String realName, String letter, Integer classId) {
        User user = new User();
        user.setUsername(username);
        user.setRole(role);
        user.setRealName(realName);
        user.setClassId(classId);
        if (Objects.equals(role, "1")) {
            user.setLetter(letter);
            return userMapper.insertUser(user) > 0 && pointsMapper.insertPointsUser(user.getUserId(), realName, 0);
        }
        return userMapper.insertUser(user) > 0;
    }

    @Override
    public int checkUserName(String username) {
        return userMapper.checkUser(username);
    }

    @Override
    @Loggable("删除用户")
    public boolean removeUser(Integer userId) {
        return userMapper.deleteUser(userId);
    }

    @Override
    public List<Integer> getAllUserIds() {
        return userMapper.selectAllUserIds();
    }

    @Override
    @Loggable("修改密码")
    public boolean modifyUserPassword(Integer id) {
        return userMapper.updateUserPassword(id) != null;
    }

    @Override
    @Loggable("修改班级")
    public Boolean modifyUserClass(Integer id, Integer grade) {
        return userMapper.updateUserClass(id,grade) != null;
    }

    @Override
    public List<User> getDepartments() {
        return userMapper.selectDepartments();
    }

    @Override
    public List<Integer> getUserByClass(String grade) {
        return userMapper.selectUserByClass(grade);
    }

}